package com.tutu.jwt.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

/**
 * @Program: SpringBoot
 * @Description: jwt的相关工具类
 * @Author: JK.TuTu
 * @ @Version: 1.0
 * @Create: 2022-11-28 19:27
 **/
public class JWTUtils {
    private static final String SINGAL = "!@#$%12345";

    /**
     * 生成token
     *
     * @param map 需要设置负载payload的具体信息
     * @return 返回生成的token
     */
    public static String createToken(Map<String, String> map) {
        Calendar calendar = Calendar.getInstance();
        //设置token的过期时间
        calendar.add(Calendar.DATE, 7);
        //创建劲jwt builder
        JWTCreator.Builder builder = JWT.create();

        //设置payload负载
        map.forEach((k, v) -> {
            builder.withClaim(k, v);
        });
        //设置令牌的过期时间
        String token = builder.withExpiresAt(calendar.getTime()).sign(Algorithm.HMAC256(SINGAL));
        return token;
    }

    /**
     * 验证token
     * @param token
     * @return
     */
    public static DecodedJWT verifyToken(String token) {
        return JWT.require(Algorithm.HMAC256(SINGAL)).build().verify(token);
    }
}
